import {
  ContentTypeEnum,
  RequestEnum,
  ResultEnum,
} from "@render/enums/httpEnum";
import { AxiosResponse } from "axios";
import { ElNotification } from "element-plus";
import { isString } from "../is";
import { setObjToUrlParams } from "../urlUtils";
import { AxiosProcessor } from "./processor";
import { RequestOptions, Result } from "./types";
import qs from "qs";
import { LAxios } from "./LAxios";

const errorNotification = (descriptions: string) => {
  ElNotification.error!({
    title: "请求错误",
    message: descriptions,
  });
};

const transform: AxiosProcessor = {
  beforeRequestHook: (config, options) => {
    const { apiUrl, joinPrefix, isParseToJson, joinParamsToUrl } = options;
    config.url = `${apiUrl || ""}${config.url}`;

    if (config.method === RequestEnum.GET) {
      //fix：重复请求不会发送问题
      const now = new Date().getTime();
      if (!isString(config.params)) {
        config.data = {
          params: Object.assign(config.params || {}, { _t: now }),
        };
      } else {
        //restFul风格
        config.url = config.url + config.params + `?_t=${now}`;
        config.params = {};
      }
    } else {
      if (!isString(config.params)) {
        config.data = config.params;
        config.params = {};
        if (joinParamsToUrl) {
          config.url = setObjToUrlParams(config.url as string, config.data);
        }
      } else {
        config.url = config.url + config.params;
        config.params = {};
      }

      if (!isParseToJson) {
        config.params = qs.stringify(config.params, {
          arrayFormat: "brackets",
        });
        config.data = qs.stringify(config.data, { arrayFormat: "brackets" });
      } else {
        config.headers = { "Content-Type": ContentTypeEnum.JSON };
      }
    }
    return config;
  },
  transformRequestData: (
    res: AxiosResponse<Result>,
    options: RequestOptions
  ) => {
    //根据自身业务进行处理
    const {} = options;
    const { data, status } = res;
    const code = status;
    if (!data) {
      return Promise.reject({
        message: "返回数据为空",
      });
    }
    if (code === ResultEnum.success) {
      return data;
    }
    return data;
  },
  requestInterceptors: (config) => {
    //token的处理
    return config;
  },
  responseInterceptors: (res) => {
    res = res.data;
    return res;
  },
  responseInterceptorsCatch: (error: any) => {
    const { data, status, statusText } = error.response || {};
    const response = data;
    const code = status;
    const message = statusText;
    const msg = response?.status !== 200 ? response?.message : "";
    const err: string = error.toString();
    try {
      if (code === "ECONNABORTED" && message.indexOf("timeout") !== -1) {
        errorNotification("接口请求超时,请刷新页面重试!");
        return;
      }
      if (err && err.includes("Network Error")) {
        errorNotification("请检查您的网络连接是否正常!");
        return;
      }
    } catch (error) {
      throw new Error(error);
    }
  },
};

const Axios = new LAxios({
  timeout: 60000,
  headers: { "Content-Type": ContentTypeEnum.FORM_URLENCODED },
  transform,
  requestOptions: {
    // 默认将prefix 添加到url
    joinPrefix: false,
    joinParamsToUrl: false,
    apiUrl: "http://wthrcdn.etouch.cn",
  },
  withCredentials: false,
});

export default Axios;
